package com.proscenic.oauth2.config.security;

import com.alibaba.fastjson.JSON;
import com.proscenic.common.web.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理逻辑
 * @version 1.0
 * created by chenxin on 2022/3/4 15:07
 */
@Slf4j
@Service
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Result result;
        if(e instanceof BadCredentialsException){
            result = Result.failed("用户名密码错误");
        }else if(e instanceof InternalAuthenticationServiceException){
            result = Result.failed("用户账号不存在");
        }else{
            result = Result.failed();
        }
//        SecurityContext context = SecurityContextHolder.getContext();
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        log.info("用户[{}]于[{}]登录失败,失败原因：[{}]", authentication.getPrincipal(), new Date(), result.getMessage());

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
